package com.debt.gateway.system.filter;


import com.debt.gateway.system.utils.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Gaozexi on 2020-7-21 22:48:35
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1 获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();

        ServerHttpResponse response = exchange.getResponse();
        //2 判断当前请求是否是登录请求，是则放行，不是则鉴权
        String path = request.getURI().getPath();
        if (path.contains("/admin/login")) {
            //放行
            return chain.filter(exchange);
        }
        //3 从请求头中获取令牌信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        //4 判断令牌是否存在
        if (StringUtils.isEmpty(token)) {
            //令牌为空，不存在，返回错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.1 存在 ，判断令牌是否合法
        try {
            //解析令牌,如果不报异常，视为合法
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }



        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
